package com.syuchen.client.udp;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;

/**
 * 案例：基于自定义同步器实现生产者消费者等待队列分离的生产者-消费者模型
 */
class ProduceConsumeQueue<T> {
    private final LinkedList<T> queue = new LinkedList<>();
    private int maxSize = 16;//最大库存

    public ProduceConsumeQueue(int maxSize) {
        this.maxSize = maxSize;
    }

    MyLock myLock = new MyLock();
    Condition producerWaitCond = myLock.newCondition();//生产者等待队列
    Condition consumerWaitCond = myLock.newCondition();//消费者等待队列

    public void put(T resource) {
        myLock.lock();
        try {
            while (queue.size() == maxSize) {
                //若库存已满，则将当前线程（生产者）加入生产者等待队列阻塞等待
                System.out.println("生产者:队列已满，无法插入...");
                producerWaitCond.await();
            }
            //否则生产一个资源，并从消费者等待队列随机唤醒一个消费者线程到同步队列参与锁竞争
            queue.addFirst(resource);
            System.out.println("生产者:插入"+resource + "! ! !");
            consumerWaitCond.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (myLock.isHeldExclusively())
                myLock.unLock();
        }
    }

    public T take() throws InterruptedException {
        myLock.lockInterruptibly();
        try {
            while (queue.size() == 0) {
                //若库存为空，则将当前线程（消费者）加入消费者等待队列阻塞等待
                System.out.println("消费者:队列为空，无法取出...");
                consumerWaitCond.await();
            }
            //否则消费一个资源，并从生产者者等待队列随机唤醒一个生产者线程到同步队列参与锁竞争
            T resource = queue.removeLast();
            System.out.println("消费者:取出消息! !!");
            producerWaitCond.signal();
            return resource;
        } finally {
            if (myLock.isHeldExclusively())
                myLock.unLock();
        }
    }
}
